<template>
  <div>
    <NavBar />
    <PostList :posts="posts" />
    <!-- 消息对话框 -->
    <el-dialog v-model="messageDialogVisible" title="留言消息">
      <div v-for="message in messages" :key="message.id">
        <p>{{ message.content }}</p>
        <p>来自: {{ message.user.username }}</p>
        <p>时间: {{ formatDate(message.createdAt) }}</p>
      </div>
      <template #footer>
        <el-button @click="messageDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useStore } from 'vuex'
import axios from '../plugins/axios'
import NavBar from '../components/NavBar.vue'
import PostList from '../components/PostList.vue'

const store = useStore()

const posts = ref([])
const messages = ref([])
const messageDialogVisible = ref(false)

// 格式化日期
const formatDate = (dateString: string) => {
  const options: Intl.DateTimeFormatOptions = {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  }
  return new Date(dateString).toLocaleDateString('zh-CN', options)
}

// 获取帖子数据
const fetchPosts = async () => {
  try {
    const response = await axios.get('/posts')
    posts.value = response.data
  } catch (error) {
    console.error('Error fetching posts:', error)
  }
}

// 获取消息数据
const fetchMessages = async (userId: string) => {
  try {
    const response = await axios.get(`/messages/unread/${userId}`)
    if (response.data && response.data.length > 0) {
      messages.value = response.data
      messageDialogVisible.value = true
    }
  } catch (error) {
    console.error('Error fetching messages:', error)
  }
}

// 在组件挂载时调用 fetchPosts 和 fetchMessages 函数
onMounted(() => {
  fetchPosts()
  const user = store.getters.getUser
  if (user && user.id) {
    fetchMessages(user.id)
  }
})

</script>

<style scoped>
</style>